package org.aplikator.client.shared.rpc.marshaller;

import org.aplikator.client.shared.data.ContainerNode;
import org.aplikator.client.shared.data.Operation;
import org.aplikator.client.shared.data.Record;
import org.jboss.errai.marshalling.client.api.Marshaller;
import org.jboss.errai.marshalling.client.api.MarshallingSession;
import org.jboss.errai.marshalling.client.api.annotations.ClientMarshaller;
import org.jboss.errai.marshalling.client.api.annotations.ServerMarshaller;
import org.jboss.errai.marshalling.client.api.json.EJObject;
import org.jboss.errai.marshalling.client.api.json.EJValue;
import org.jboss.errai.marshalling.client.marshallers.AbstractNullableMarshaller;

@ClientMarshaller(ContainerNode.class)
@ServerMarshaller(ContainerNode.class)
public class ContainerNodeMarshaller extends AbstractNullableMarshaller<ContainerNode> {

	/*@Override
	public Class<ContainerNode> getTypeHandled() {
		return ContainerNode.class;
	}*/

	@Override
	public ContainerNode[] getEmptyArray() {
		return new ContainerNode[0];
	}

	@Override
	public ContainerNode doNotNullDemarshall(EJValue o, MarshallingSession ctx) {
		if (o.isObject() != null) {
			ContainerNode cnode = new ContainerNode();
			EJObject ejObject = o.isObject();
			if (DemarshallingUtils.containsAndNotNull(ejObject, "viewId")) {
				cnode.setViewId(ejObject.get("viewId").isString().stringValue());
			}
			if (DemarshallingUtils.containsAndNotNull(ejObject, "operation")) {
				cnode.setOperation(Operation.valueOf(ejObject.get("operation").isString().stringValue()));
			}			
			
			Marshaller<Object> recMarshaller = ctx.getMarshallerInstance(Record.class.getName());
			cnode.setOriginal((Record) recMarshaller.demarshall(ejObject.get("original"), ctx));
			cnode.setEdited((Record) recMarshaller.demarshall(ejObject.get("edited"), ctx));

			return cnode;
			
		} else return null;
	}

	@Override
	public String doNotNullMarshall(ContainerNode o, MarshallingSession ctx) {
		StringBuilder builder = new StringBuilder().append('{');
		MarshallingUtils.string("viewId", o.getViewId(), builder).append(',');
		MarshallingUtils.string("operation", o.getOperation().name(), builder).append(',');
		
		Marshaller<Object> recMarshaller = ctx.getMarshallerInstance(Record.class.getName());
		MarshallingUtils.key("original", builder).append(':');
		builder.append(recMarshaller.marshall(o.getOriginal(), ctx)).append(',');
	
		MarshallingUtils.key("edited", builder).append(':');
		builder.append(recMarshaller.marshall(o.getEdited(), ctx));

		builder.append('}');
		return builder.toString();
	}
}
